/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package towerz.states;

import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.game.GameCanvas;
import towerz.Main;
import towerz.game.Score;
import towerz.system.BitmapFont;
import towerz.system.MobileHttp;
import towerz.system.StateManager;
import towerz.system.StringManager;
import towerz.system.Utilities;
import towerz.system.HighScoreReaderWriter;

/**
 *
 * @author TimotiusNC
 */
public class StateHighScore extends GameState implements CommandListener {
	public static final int SAVE_REQUEST = 0;
	public static final int SHOW_REQUEST = 1;

	public static final int NOT_SENT = 0;
	public static final int SENT_FAILED = 1;
	public static final int SENT_SUCCESS = 2;

	//0 -> requestType
	//1 -> score (optional)

	public StateHighScore(){
		super(GameState.HIGH_SCORE, StateManager.instance().getBackgroundImage());
		initComp();
	}

	public StateHighScore(Vector params){ //CTOR for SHOW request
		super(GameState.HIGH_SCORE, StateManager.instance().getBackgroundImage());
		m_RequestType	= Integer.parseInt(params.elementAt(0).toString());
		if(m_RequestType == SAVE_REQUEST) //Get score to save
			m_ScoreToSave		= Integer.parseInt(params.elementAt(1).toString());

		initComp();
	}

	private void initComp(){
		m_HasDrawn		= false;

		if(m_RequestType == SHOW_REQUEST) {
			m_HasFetched	= false;
			m_HasRequested	= false;

			//Get local highscore
			m_LocalScoreList = HighScoreReaderWriter.readOneScoreRecords(Utilities.HIGH_SCORE_RMS);
		} else {
			m_HasSentScore	= false;
			m_HasSentScorePleaseWaitDrawn = false; //Setelah user klik send, pesan 'please wait' belum tergambar
			m_SendingStatus	= NOT_SENT; //Belum dikirim
		}

		m_ReturnImage	= BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(StringManager.instance().getString("return"), 0x00000000);
		m_TitleImg		= BitmapFont.getFont(BitmapFont.TITLE).renderTransparentText(StringManager.instance().getString("highscore"), 0x00000000);
		m_PleaseWaitImg	= BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(StringManager.instance().getString("pleasewait"), 0x00000000);
		m_NoConnImg		= BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(StringManager.instance().getString("noconn"), 0x00000000);

		m_LocalHSImg	= BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(StringManager.instance().getString("localhighscore"), 0x00000000);
	}

	private void initSaveComp(){
		//initComp
		m_OKImg			= BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText("OK", 0x00000000);
		m_EnterNameImg	= BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(StringManager.instance().getString("entername"), 0x00000000);
		m_YourScoreImg	= BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(StringManager.instance().getString("yourscore"), 0x00000000);
		m_PressFireToEditImg = BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(StringManager.instance().getString("pressfiretoedit"), 0x00000000);

		//Username, command
		m_UsernameToSave	= "NULL";
		m_OKCommand			= new Command("OK", Command.OK, 1);

		//Set Command and Listener
		m_TextBox			= new TextBox("Enter your username", "", 10, TextField.ANY);
		m_TextBox.addCommand(m_OKCommand);
		m_TextBox.setCommandListener(this);
	}

	private void initShowComp(){
		m_ScoreList = new Vector();

		//Fetch Highscore online
		String rawHighScore;
		try{ //Populate m_ScoreList by requesting the server;
			rawHighScore = MobileHttp.getInstance().sendUsingGet(Utilities.SERVER + "/gethighscore.php", null);
		} catch (Exception e){
			rawHighScore = "error";
		}

		m_HasFetched = true;
		if(!rawHighScore.equals("error") && rawHighScore.endsWith(";")){
			String[] allHighScores = Utilities.split(rawHighScore, ";");

			for(int i=0; i<allHighScores.length; ++i){
				String[] oneScore = Utilities.split(allHighScores[i], "#");
				m_ScoreList.addElement(new Score(oneScore[0], Integer.parseInt(oneScore[1])));
			}
		}
	}

	private void saveHighScore(String username, int score){
		String response = "";
		Score scoreToSave = new Score(username, score);

		//Save score to RMS
		HighScoreReaderWriter.addRecordToRms(new Score(username, score), Utilities.HIGH_SCORE_RMS);

		//Send score to the server
		Hashtable param = new Hashtable();
		param.put("name", scoreToSave.getUsername());
		param.put("score", String.valueOf(scoreToSave.getScore()));
		try{
			response = MobileHttp.getInstance().sendUsingPost(Utilities.SERVER + "/uploadscore.php", param);
		} catch(Exception e){
			response = "error";
		}

		if(response.equals("success"))
			m_SendingStatus = SENT_SUCCESS;
		else
			m_SendingStatus = SENT_FAILED;
	}

	public void keyPressed(int key){
		//Super
		super.keyPressed(key);

		if (key == -7 || key == 35) {
			StateManager.instance().goTo(GameState.FRONT, null, true);

			//Back sound effect
			StateManager.instance().playSFX("/cancel.wav");
		}

		if(key == -6 && m_RequestType == SAVE_REQUEST) {
			if(!m_HasSentScore)
				m_HasSentScore = true;
		}
	}

	public void update(long time, int keys) {
		//Super
		super.update(time, keys);

		if(m_HasDrawn && !m_HasRequested){
			if(m_RequestType == SAVE_REQUEST)	initSaveComp();
			else								initShowComp();

			m_HasRequested = true;
		}

		if(m_SendingStatus == NOT_SENT && m_HasSentScorePleaseWaitDrawn)
			saveHighScore(m_UsernameToSave, m_ScoreToSave);

		if( ((keys & GameCanvas.FIRE_PRESSED) != 0) && m_RequestType == SAVE_REQUEST && m_SendingStatus == NOT_SENT){
			Display.getDisplay(Main.Midlet).setCurrent(m_TextBox);
		}
	}

	public void draw(Graphics g){
		//Super
		super.draw(g);

		g.drawImage(StateManager.instance().getDarkImage(), 0, 0, Graphics.LEFT | Graphics.TOP);
		g.drawImage(m_TitleImg, StateManager.instance().getWidth() / 2, 10, Graphics.HCENTER | Graphics.TOP);
		g.drawImage(m_ReturnImage, StateManager.instance().getWidth() - 4, StateManager.instance().getHeight()-4, Graphics.RIGHT | Graphics.BOTTOM);

		if(m_RequestType == SHOW_REQUEST) {
			g.drawImage(m_LocalHSImg, 10, 125, Graphics.LEFT | Graphics.TOP);

			if(m_LocalScoreList != null){
				for(int i=0; i<1; ++i){ //Just show the highest one
					//g.drawImage(BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(((Score)m_LocalScoreList[i]).getUsername(), 0x00000000), 50, 140 + i*15, Graphics.TOP | Graphics.LEFT);
					//g.drawImage(BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(String.valueOf(((Score)m_LocalScoreList[i]).getScore()), 0x00000000), StateManager.instance().getWidth() - 80, 140 + i*15, Graphics.TOP | Graphics.RIGHT);
					g.drawImage(BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(String.valueOf(((Score)m_LocalScoreList[i]).getScore()), 0x00000000), StateManager.instance().getWidth()/2, 140 + i*15, Graphics.HCENTER | Graphics.TOP);
				}
			} else {
				g.drawImage(BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(StringManager.instance().getString("nooneplay"), 0x00000000), StateManager.instance().getWidth() - 80, 50 + 200, Graphics.TOP | Graphics.RIGHT);
			}
		}

		if(m_HasDrawn){
			if(m_RequestType == SAVE_REQUEST){
				if(!m_HasSentScore){ //User has not pressed button to send the score
					g.drawImage(m_OKImg, 4, StateManager.instance().getHeight()-4, Graphics.LEFT | Graphics.BOTTOM);
					g.drawImage(m_YourScoreImg, 5, 40, Graphics.LEFT | Graphics.TOP);
					g.drawImage(BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(String.valueOf(m_ScoreToSave), 0x00000000), 20, 60, Graphics.LEFT | Graphics.TOP);

					g.drawImage(m_EnterNameImg, 5, 80, Graphics.LEFT | Graphics.TOP);
					g.setColor(0xFFBD7531);
					g.fillRect(5, 100, StateManager.instance().getWidth() - 10, 20);

					if(m_UsernameToSave.equals("NULL"))
						g.drawImage(BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText("enter name", 0x00000000), 7, 100, Graphics.LEFT | Graphics.TOP);
					else
						g.drawImage(BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(m_UsernameToSave, 0x00000000), 7, 100, Graphics.LEFT | Graphics.TOP);

					g.drawImage(m_PressFireToEditImg, 5, 120, Graphics.LEFT | Graphics.TOP);
				} else {//Sending highscore to the server
					if(m_SendingStatus == NOT_SENT){
						g.drawImage(m_PleaseWaitImg, StateManager.instance().getWidth() / 2, 60, Graphics.HCENTER | Graphics.VCENTER);
						m_HasSentScorePleaseWaitDrawn = true;
					}
					else if (m_SendingStatus == SENT_FAILED) //Failed
						g.drawImage(m_NoConnImg, StateManager.instance().getWidth() / 2, 60, Graphics.HCENTER | Graphics.VCENTER);
					else //Success
						g.drawImage(BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(StringManager.instance().getString("scoreuploaded"), 0x00000000), StateManager.instance().getWidth() / 2, 60, Graphics.HCENTER | Graphics.VCENTER);
				}
			} else { //SHOW_REQUEST
				if(m_HasFetched){
					if(m_ScoreList.size() > 0){
						for(int i=0; i<m_ScoreList.size(); ++i){
							g.drawImage(BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(((Score)m_ScoreList.elementAt(i)).getUsername(), 0x00000000), 50, 45 + i*15, Graphics.TOP | Graphics.LEFT);
							g.drawImage(BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(String.valueOf(((Score)m_ScoreList.elementAt(i)).getScore()), 0x00000000), StateManager.instance().getWidth() - 80, 45 + i*15, Graphics.TOP | Graphics.RIGHT);
						}
					} else { //Fetching failed
						g.drawImage(m_NoConnImg, StateManager.instance().getWidth() / 2, 60, Graphics.HCENTER | Graphics.VCENTER);
					}
				} else { //Fetching highscores from server
					g.drawImage(m_PleaseWaitImg, StateManager.instance().getWidth() / 2, 60, Graphics.HCENTER | Graphics.VCENTER);
				}
			}
		} else {
			if(m_RequestType == SHOW_REQUEST) //Show please wait
				g.drawImage(m_PleaseWaitImg, StateManager.instance().getWidth() / 2, 60, Graphics.HCENTER | Graphics.VCENTER);
		}
		
		m_HasDrawn = true;
	}

	//PROPERTIES
	protected boolean	m_HasDrawn, m_HasFetched, m_HasRequested, m_HasSentScore, m_HasSentScorePleaseWaitDrawn; //The hell lahh apa2an iniii nama variable nya
	protected int		m_RequestType, m_SendingStatus;
	protected Image		m_ReturnImage, m_TitleImg, m_OKImg, m_YourScoreImg, m_EnterNameImg, m_PressFireToEditImg, m_NoConnImg, m_PleaseWaitImg;
	protected Image		m_LocalHSImg;
	
	//SHOW request
	protected Vector	m_ScoreList;
	protected Score[]	m_LocalScoreList;

	//SAVE request
	protected String	m_UsernameToSave;
	protected int		m_ScoreToSave;
	protected Form		m_InputNameForm;
	protected TextBox	m_TextBox;
	protected Command	m_OKCommand;

	public void commandAction(Command c, Displayable d) {
		if(c == m_OKCommand){
			Display.getDisplay(Main.Midlet).setCurrent(StateManager.instance());

			if(m_TextBox.getString().equals(""))
				m_UsernameToSave = "NULL";
			else
				m_UsernameToSave = m_TextBox.getString();
		}
	}
}
